package com.example.demo.service.weCon.impl;

import com.example.demo.config.BaseMessageConf;
import com.example.demo.config.WeConConfig;
import com.example.demo.entity.DTO.TokenDTO;
import com.example.demo.entity.DTO.WeConTokenDTO;
import com.example.demo.enums.WeConFunctionType;
import com.example.demo.service.weCon.WeConService;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.WeChatHttpClient;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 企业微信实现类
 *
 * @author jack
 * @data 2021/8/11 4:01 下午
 */
@Service
public class WeConServiceImpl implements WeConService {

  @Autowired
  private RedisUtil redisUtil;

  public final static String TOKEN = "token:";

  @Override
  public String getToken(@NotNull(message = "functionType 不能为空") WeConFunctionType functionType) {
    // 1 redis获取token/保存token
    // 1.1redis获取token
    String key = TOKEN + functionType;
    String token = redisUtil.getKey(key);
    if (StringUtils.isNotBlank(token)) {
      return token;
    }
    // 1.2 微信api获取token
    TokenDTO tokenDTO = new TokenDTO();
    tokenDTO.setCorpid(WeConConfig.ID);
    switch (functionType) {
      case CONTACTS_MANAGEMENT:
        tokenDTO.setCorpsecret(WeConConfig.ContactsManagement.ACCESS_TOKEN);
        break;
      default:
        throw new RuntimeException(BaseMessageConf.ENUMS_NOT_EXIST);
    }
    WeConTokenDTO weConTokenDTO = WeChatHttpClient
        .doGetByEntity(WeConConfig.GET_TOKEN, tokenDTO, WeConTokenDTO.class);

    System.out.println(weConTokenDTO);
    // 1.3 保存到redis  expires_in -10秒防止 过期
    Integer expireTime = weConTokenDTO.getExpires_in() - 10;
    redisUtil.setKey(key, weConTokenDTO.getAccess_token(), Long.parseLong(expireTime.toString()));
    return weConTokenDTO.getAccess_token();
  }

  @Override
  public String generateWeConUrl(@NotNull String url,
      @NotNull(message = "functionType 不能为空") WeConFunctionType functionType) {
    String token = this.getToken(functionType);
    return String.format("%s?access_token=%s", url, token);
  }

  @Override
  public String generateWeConUrl(@NotNull String url,
      @NotNull(message = "functionType 不能为空") WeConFunctionType functionType,
      Map<String, Object> paramMap) {
    String backUrl = this.generateWeConUrl(url, functionType);
    if (!paramMap.isEmpty()) {
      String params = paramMap.entrySet().stream()
          .map(m -> String.format("&%s=%s", m.getKey(), m.getValue()))
          .collect(Collectors.joining());
      return backUrl + params;
    }
    return backUrl;
  }
}
